let productList = [] //所有商品列表数据
/**
 * 获取商品列表数据
 */
function getProductList(pageNo = 1) {
	// 使用axios库发起网络请求
	requestGoodsList(pageNo).then(res => {
		let {
			resultCode,
			resultInfo
		} = res.data
		if (resultCode == 1) {
			productList = [...productList, ...resultInfo.list]
			showProductList(productList)
		}
	})
}
/**
 * 动态渲染商品列表
 */
function showProductList(productList = []) {
	// let list = productList.map(item => {
	// 	return `<div class="product-item" onclick="onDetail(${item.id})">
    //                 <img src="${item.picture}" alt="pic1">
    //                 <p>${item.product}</p>
    //                 <p>￥${item.price}  ${item.putaway}人已买</p>
    //             </div>`
	// })
	console.log(productList[0]);
	let list = productList.map(item => {
        return `
        <ul onclick="onDetail(${item.id})"  class="product-item">
            <li><img src="${item.picture}"
                    alt="pic1"></li>
            <li class="textarea">${item.product}</li>
            <span class="sp1">淘宝</span><span class="sp2">${item.putaway?"包邮":"不包邮"}</span><br>
            <span class="sp3">￥${item.price}</span><span class="sp4">${item.oldprice}人已买</span><span class="sp5">${item.categoryname}</span>

        </ul>
        `
    })
	const rootEle = document.querySelector('.container')
	rootEle.innerHTML = list.join('')

	// 移动阴影
	const ulEles = document.querySelectorAll(".container>.product-item")
	for(let i =0;i<ulEles.length;i++){
        ulEles[i].addEventListener("mouseover",function(){
            this.style.boxShadow = "10px 10px 5px #888888"
        })
        ulEles[i].addEventListener("mouseout",function(){
            this.style.boxShadow = ""
        })
    }
}

/**
 * 跳转详情页
 * @param {*} id
 */
function onDetail(id) {
	// 跳转详情页
	location.href = './detail.html?id=' + id
}

/**
 * 注册跳转
 */
function bindSign() {
	const sign = document.querySelector('.sign')
	sign.addEventListener('click', function () {
		location.href = './sign.html'
	})
}

/**
 * 登录
 */
function bindLogin() {
	const login = document.querySelector('.login')
	const loginForm = document.querySelector('.login_wraper')
	const closeEle = document.querySelector('.login_wraper .close')
	const userInput = document.querySelector('input[name="username"]')
	const passwordInput = document.querySelector('input[name="password"]')

	login.addEventListener('click', function () {
		loginForm.style.display = 'block'
	})

	closeEle.addEventListener('click', function () {
		loginForm.style.display = 'none'
	})

	loginForm.addEventListener('submit', function (e) {
		e = e || window.event
		e.preventDefault() // 阻止默认行为

		let username = userInput.value
		let password = passwordInput.value

		requestLogin(username, password).then(res => {
			// 登录成功
			let {
				resultCode,
				resultInfo
			} = res.data
			if (resultCode == 1) {
				let user = resultInfo
				showUser(user)
				// 保存用户状态信息
				let userInfo = {
					username: user.username,
					nick: user.nick,
					id: user.uid,
					headerimg: user.headerimg,
				}
				Cookies.set('user', JSON.stringify(userInfo), {
					expires: 1
				})
			} else {
				alert('用户名或密码出错')
			}
			loginForm.style.display = 'none' // 关闭登录界面
		})
	})
}

/**
 * 判断用户是否登录，如果登录显示个人中心
 * @param {*} user
 */
function showUserMessage() {
	let user = Cookies.get('user')
	if (user) {
		showUser(JSON.parse(user))
	}
}

/**
 * 显示个人中心
 */
function showUser(user) {
	let str = `
				<img src="${user.headerimg}" alt="">
				<p>${user.username}</p>
				<button onclick="onLogout()">注销</button>
			`
	const wraper = document.querySelector('.wraper')
	wraper.innerHTML = str
}

function onLogout() {
	// 注销清除cookie
	Cookies.remove('user')

	let str = `  
					<button class="sign">注册</button>
					<button class="login">登录</button>
				`
	const wraper = document.querySelector('.wraper')
	wraper.innerHTML = str
}

/**
 * 加载更多
 */
function bindLoadMore() {
	const moreBtn = document.querySelector('.more>button')
	let pageNo = 1
	moreBtn.addEventListener('click', function () {
		getProductList(++pageNo)
	})
}

getProductList(1)
bindSign()
bindLogin()
showUserMessage()
bindLoadMore()

/**
 * 右侧功能区
 * 	顶部 分区 底部 
 */
function rightBtnList() {
	const btnList = document.querySelectorAll(".right-fixed>div")
	btnList[0].addEventListener("click", function () {
		let s1
		if (s1) {
			clearInterval(s1)
		}
		s1 = setInterval(() => {
			document.documentElement.scrollTop -= 50
			if (document.documentElement.scrollTop == 0) {
				clearInterval(s1)
			}
		}, 15);
	})
	btnList[1].addEventListener("click", function () {

	})
	btnList[2].addEventListener("click", function () {
		document.documentElement.scrollTop = 300
	})
	btnList[3].addEventListener("click", function () {
		document.documentElement.scrollTop = 650

	})
	btnList[4].addEventListener("click", function () {
		document.documentElement.scrollTop = 6000
		// let s2
		// if(s2){
		//     clearInterval(s2)
		// }
		// s2 = setInterval(() => {
		//     document.documentElement.scrollTop +=50
		//     console.log(document.documentElement.scrollTop);
		//     if(document.documentElement.scrollTop >= 5000){
		//         clearInterval(s1)
		//     }
		// }, 50);
	})


	// for (let i = 0; i < btnList.length; i++){
	//     btnList[i].addEventListener("click",function(){

	//     })
	// }
}
rightBtnList()


/** 
 * 导航点击区
 *  =>选项卡，跳转首页， 未做跳转分页
*/
function bindChoseNav(){
	const navUl = document.querySelector("#nav>ul")
	navUl.addEventListener("click",function(e){
		e = e || e.window
		let target = e.target || e.srcElement
		const navLis = document.querySelectorAll("#nav>ul>li")
		navLis.forEach(itme=>itme.className="")
		target.className = "chosed"
	})
}
bindChoseNav()

/**
 * 分类列表区
 *   =>选项卡 事件委托          分页有点多没做
*/
function bindBannerList(){
	const ulEle = document.querySelector(".leftList>ul")
	const rightNav = document.querySelector(".leftList>.rightNav")
	ulEle.addEventListener("mouseover",function(){
		rightNav.style.display = "block"
	})
	ulEle.addEventListener("mouseout",function(){
		rightNav.style.display = "none"
	})
}
bindBannerList()


/* 倒计时        有错误 */
// function daojiTime(a, b) {
// 	var time1 = new Date()
// 	var time2 = new Date(a)
// 	var time = time2.getTime() - time1.getTime() // 总的毫秒差 = 天的毫秒差

// 	// 换算-天  相差的总毫秒/ 1天的毫秒 = 相差的天数
// 	var day = time / (1000 * 60 * 60 * 24)
// 	day = Math.floor(day)
// 	if (day < 10) day = "0" + day // 判断是否个位数 是则前面加个0  07：04：46：55

// 	var hoursTime = time - day * (1000 * 60 * 60 * 24)
// 	var hours = hoursTime / (1000 * 60 * 60)
// 	hours = Math.floor(hours)
// 	if (hours < 10) hours = "0" + hours

// 	var minutesTime = hoursTime - hours * (1000 * 60 * 60)
// 	var minutes = minutesTime / (1000 * 60)
// 	minutes = Math.floor(minutes)
// 	if (minutes < 10) minutes = "0" + minutes

// 	var secondsTime = minutesTime - minutes * (1000 * 60)
// 	var seconds = secondsTime / (1000)
// 	seconds = Math.floor(seconds)
// 	if (seconds < 10) seconds = "0" + seconds

// 	var str = `<span>${hours}</span> : <span>${minutes}</span> : <span>${seconds}</span> `

// 	if (day == "00" && hours == "00" && minutes == "00" && seconds == "00" || !seconds) {
// 		return `${b} 已结束`
// 	}
// 	return str
// }
// console.log(daojiTime(`2022-10-8 14:25:30`, `结束`));
// let p1 = document.querySelector(".daojiTime>p")
// setInterval(function () {
// 	p1.innerHTML = 1 
// 	console.log(1);
// }, 500)